﻿using DNFImagePacks2Manager.Helpers;
using Microsoft.UI.Xaml.Controls;
using System;
using System.Collections.Generic;
using System.IO;

namespace DNFImagePacks2Manager.Models
{
    public abstract class NPKCustomBase : PinYinItem
    {
        public string Suffix { get; private set; }
        public string BasePath { get; }
        public string CsmFile => Path.Combine(BasePath, FullName);
        public string FullName => Name + Suffix;

        public NPKCustomBase(string filename, string? basePath = null)
        {
            Name = Path.GetFileNameWithoutExtension(filename);
            Suffix = Path.GetExtension(filename);
            BasePath = basePath ?? CustomHelper.GetCustomFolder();
        }

        public abstract List<string> GetNPKNameList();
        public abstract List<NPKItemBase> GetNPKItemList();

        public void View(Page page)
        {
            List<string> npkNameList = GetNPKNameList();

            ListView listView = new()
            {
                ItemsSource = npkNameList
            };

            DialogHelper.ShowNormalDialog(page, $"{Name} ({npkNameList.Count})", listView);
        }

        public async void Apply(Page page)
        {
            if (!LocalStorageHelper.IsSetDNFPath())
            {
                DialogHelper.ShowErrorMessage(page, "应用失败: 未设置DNF路径");
                return;
            }

            CheckBox checkBox = new()
            {
                Content = "应用配置时禁用其他补丁"
            };

            StackPanel stackPanel = new();
            stackPanel.Children.Add(checkBox);

            ContentDialogResult result = await DialogHelper.ShowConfirmDialog(page, Name, stackPanel);

            if (result == ContentDialogResult.Primary)
            {
                bool disableOtherNPK = checkBox.IsChecked ?? false;

                Apply(disableOtherNPK);

                DialogHelper.ShowSuccessMessage(page, $"个性化配置 '{Name}' 已应用");
            }
        }

        public void Apply(bool disableOtherNPK)
        {
            if (disableOtherNPK)
            {
                List<NPKItemBase> npkItems = NPKListHelper.GetEnabledAllList();
                foreach (var item in npkItems)
                {
                    if (item.Status)
                    {
                        item.DisableNPK();
                    }
                }
            }

            List<NPKItemBase> npkList = GetNPKItemList();
            foreach (NPKItemBase item in npkList)
            {
                if (item != null && !item.Status)
                {
                    item.EnableNPK();
                }
            }
        }

        public void Edit(Page page)
        {
            if (File.Exists(CsmFile)) {
                ConsoleHelper.OpenFileInNotepad(CsmFile);
            }
        }

        public bool Rename(Page page, string newName)
        {
            string customFolder = CustomHelper.GetCustomFolder();

            if (File.Exists(Path.Combine(customFolder, newName + Suffix)))
            {
                DialogHelper.ShowErrorMessage(page, "文件名已存在，请使用其他名称");
                return false;
            }

            try
            {
                FileHelper.RenameFile(customFolder, FullName, newName + Suffix);
                this.Name = newName;
                return true;
            }
            catch (Exception)
            {
                DialogHelper.ShowErrorMessage(page, "重命名失败，请确保文件未被其他程序占用");
                return false;
            }
        }

        public bool Delete()
        {
            try
            {
                if (File.Exists(CsmFile))
                {
                    File.Delete(CsmFile);
                }

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public void Export(Page page)
        {
            if (!LocalStorageHelper.IsSetDNFPath())
            {
                DialogHelper.ShowErrorMessage(page, "导出失败: 未设置DNF路径");
                return;
            }

            if (!File.Exists(CsmFile))
            {
                DialogHelper.ShowErrorMessage(page, "个性化配置文件不存在，请重试");
                return;
            }

            List<NPKItemBase> npkList = GetNPKItemList();

            if (npkList.Count == 0)
            {
                DialogHelper.ShowErrorMessage(page, "个性化配置中无补丁文件信息，请重试");
                return;
            }

            string NPKPath = LocalStorageHelper.GetImagePath();

            Dictionary<string, string> compressFiles = [];

            foreach (var npkItem in npkList)
            {
                string? npkFile = null;
                if (npkItem != null)
                {
                    if (npkItem.Status)
                    {
                        if (File.Exists(npkItem.EnableFile))
                        {
                            npkFile = npkItem.EnableFile;
                        }
                    }
                    else
                    {
                        if (File.Exists(npkItem.DisableFile))
                        {
                            npkFile = npkItem.DisableFile;
                        }
                    }

                    if (npkFile == null)
                    {
                        continue;
                    }

                    compressFiles.Add(npkItem.EnableName, npkFile);
                }
            }

            if (compressFiles.Count == 0)
            {
                DialogHelper.ShowErrorMessage(page, "个性化配置中无有效补丁文件信息，请重试");
                return;
            }

            compressFiles.Add(FullName, CsmFile);

            DialogHelper.ShowSavePickerAndExportZip(page, Name, compressFiles);
        }
    }
}
